<template>
  <div>
    <Card>
      <Button type="primary" @click="showAddModal" class="mr10">添加账单</Button>
      <Button type="primary" :loading="refreshLoading" @click="refreshEvent" shape="circle" icon="md-refresh"
        class="fr"></Button>
      <Select v-model="searchTypeValue" class="searchInputClass">
        <Option v-for="item in searchType" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select>
      <Input v-model="searchKeyWord" placeholder="请输入搜索关键字" :type="searchInputType" suffix="ios-search"
        class="searchKeyWordInputClass" />
    </Card>
    <!--表格start-->
    <Card>
      <Tables ref="tables" v-model="searchData" :columns="columns" :loading="loading" :border="true" size="large" />
    </Card>
    <!--表格end-->

    <!--分页start-->
    <Page :total="num" @on-change="changePage" show-sizer show-elevator show-total :page-size="pageSize"
      :page-size-opts="$store.state.pageSizeArray" @on-page-size-change="changePageSize"
      style="margin-top: 12px; float: right" />
    <!--分页end-->

    <!--添加数据模态框start-->
    <Modal title="添加数据" v-model="addModal" :styles="{ top: '50px' }" @on-ok="addDataEventOk">
      <Form :model="addData" :label-width="100" :rules="ruleValidate">
        <FormItem label="日期：" prop="date">
          <Input v-model="addData.date" type="date" placeholder="请选择日期." class="inputWidth200"></Input>
        </FormItem>
        <FormItem label="商品：" prop="name">
          <Radio-group v-model="addData.name" type="button" size="large" >
            <Radio class="mb10" v-for="value in goodsNameType" :key="value" :label="value"></Radio>
          </Radio-group>
        </FormItem>
        <FormItem label="金额：" prop="money">
          <Input-number :max="10000" :min="0" v-model="addData.money" autoFocus :step="1"></Input-number>
        </FormItem>
        <FormItem label="支付方式：" prop="mode">
          <Select v-model="addData.mode">
            <Option value="0">微信</Option>
            <Option value="1">支付宝</Option>
            <Option value="2">银行卡</Option>
          </Select>
        </FormItem>

        <FormItem label="备注：">
          <Input v-model="addData.remarks" maxlength="100" show-word-limit type="textarea"
            placeholder="请输入内容，字数在1-100位之间." :rows="4"></Input>
        </FormItem>
      </Form>
    </Modal>
    <!--添加数据模态框end-->

    <Modal title="修改数据" v-model="editModal" :styles="{ top: '50px' }" @on-ok="editDataEvent"
      @on-cancel="editDataEventCancel">
      <Form :model="editData" :label-width="100" :rules="ruleValidate">
        <FormItem label="日期：" prop="date">
          <Input v-model="editData.date" type="date" placeholder="请选择日期。" class="inputWidth200"></Input>
        </FormItem>
        <FormItem label="商品：" prop="name">
          <!-- <Input
            v-model="editData.name"
            maxlength="30"
            type="text"
            placeholder="请输入商品名称或消费类型，字数在1-20位之间。"
          ></Input>-->
          <Radio-group v-model="editData.name" type="button" size="large">
            <Radio class="mb10" v-for="value in goodsNameType" :key="value" :label="value"></Radio>
          </Radio-group>
        </FormItem>
        <FormItem label="金额：" prop="money">
          <Input-number :max="10000" :min="0" v-model="editData.money" :step="1"></Input-number>
        </FormItem>
        <FormItem label="支付方式：" prop="mode">
          <Select v-model="editData.mode">
            <Option value="0">微信</Option>
            <Option value="1">支付宝</Option>
            <Option value="2">银行卡</Option>
          </Select>
        </FormItem>

        <FormItem label="备注：">
          <Input v-model="editData.remarks" maxlength="100" show-word-limit type="textarea" placeholder="请输入内容，不超过100字。"
            :rows="4"></Input>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import {
  getAccountingData,
  addAccountingData,
  deleteAccountingData,
  editAccountingData,
} from "@/api/content/accounting/consume.js";
export default {
  components: {
    Tables,
  },
  data() {
    return {
      goodsNameType: ["餐饮", "超市", "网购", "交通", "门票", "住房", "其他"],
      ruleValidate: {
        date: [
          {
            required: true,
            message: "您未选择日期或格式不正确，请重新选择.",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "您输入的商品名称不能为空，字数在1-6位之间，请重新输入.",
            trigger: "blur",
          },
        ],
        mode: [
          {
            required: true,
            message: "您未选择支付方式或格式不正确，请重新选择.",
            trigger: "blur",
          },
        ],
      },
      refreshLoading: false,
      num: 0,
      //表格列
      columns: [
        {
          title: "#",
          key: "id",
          width: 200,
          align: "center",
          sortable: true,
        },
        {
          title: "日期",
          key: "date",
          width: 200,
          align: "center",
          sortable: true,
        },
        { title: "商品", key: "name", width: 200, align: "center" },
        {
          title: "金额",
          key: "money",
          width: 100,
          align: "center",
          sortable: true,
        },
        {
          title: "方式",
          key: "mode",
          width: 100,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                params.row.mode == 0
                  ? "微信"
                  : params.row.mode == 1
                    ? "支付宝"
                    : "银行卡"
              ),
            ]);
          },
        },
        { title: "备注", key: "remarks" },
        {
          title: "操作",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.editData = params.row;
                      this.editData.money = parseFloat(this.editData.money);
                      this.showEditModal();
                    },
                  },
                },
                "修改"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    type: "error",
                    size: "large",
                    title: "你确定要删除吗?",
                  },

                  on: {
                    "on-ok": () => {
                      this.deleteDataEvent(params.row);
                    },
                    "on-cancel": () => {
                      this.$Message.info("您取消了删除.");
                    },
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "warning",
                      },
                      style: {
                        marginRight: "5px",
                      },
                    },
                    "删除"
                  ),
                ]
              ),
            ]);
          },
        },
      ],
      //搜索类型
      searchType: [
        {
          label: "日期",
          value: "date",
        },
        {
          label: "商品名称",
          value: "name",
        },
        {
          label: "金额",
          value: "money",
        },
        {
          label: "支付方式",
          value: "mode",
        },
        {
          label: "备注",
          value: "remarks",
        },
      ],
      //搜索类型值
      searchTypeValue: "date",
      //搜索关键字
      searchKeyWord: "",
      searchInputType: "date",
      tableData: [],
      //分页
      num: 0,
      pageCurrent: 1,
      pageSize: 10,
      loading: true,
      //添加数据
      addData: { date: "", name: "餐饮", mode: "1", money: null, remarks: "" },
      //添加数据模态框状态
      addModal: false,
      //修改数据
      editData: {},
      //修改数据模态框状态
      editModal: false,
    };
  },
  computed: {
    searchData() {
      if (!this.searchKeyWord) {
        return this.tableData;
      }
      return this.tableData.filter((item) => {
        return item[this.searchTypeValue].indexOf(this.searchKeyWord) !== -1;
      });
    },
  },
  methods: {
    //添加数据
    addDataEventOk(e) {
      if (!this.requireFormData(this.addData)) {
        return;
      } else {
        addAccountingData(this.addData)
          .then((res) => {
            if (res.data.code == 0) {
              this.getData(this.pageCurrent, this.pageSize);
              this.addData.remarks = "";
              this.addData.money = null;
              this.$Message.success("您成功添加了一条数据.");
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您添加数据失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch((err) => {
            this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },
    editDataEventCancel() {
      this.getData(this.pageCurrent, this.pageSize);
    },
    refreshEvent() {
      this.refreshLoading = true;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //删除数据
    deleteDataEvent(row) {
      deleteAccountingData(row.id)
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData.splice(row["_index"], 1);
            this.$Message.success("您成功删除了一条数据.");
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error("您删除数据失败了，错误原因：" + res.data.msg);
          }
        })
        .catch((err) => {
          this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
        });
    },

    //修改数据
    editDataEvent() {
      if (!this.requireFormData(this.editData)) {
        this.getData(this.pageCurrent, this.pageSize);
        return;
      } else {
        editAccountingData(this.editData)
          .then((res) => {
            if (res.data.code === 0) {
              this.getData(this.pageCurrent, this.pageSize);
              this.$Message.success("您成功修改了一条数据.");
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您修改数据失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch((err) => {
            this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },

    //查询数据
    getData(page, pageNum) {
      this.loading = true;
      getAccountingData(page, pageNum)
        .then((res) => {
          if (res.data.code == 0) {
            this.num = res.data.num;
            this.tableData = res.data.data;
            this.loading = false;
            this.refreshLoading = false;
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "自动获取数据失败了，错误原因：" + res.data.msg
            );
          }
        })
        .catch((err) => {
          this.$Message.warning("服务器异常，请稍后重试.错误原因：" + err);
        });
    },
    //打开添加模态框
    showAddModal() {
      this.addModal = true;
    },

    //打开修改模态框
    showEditModal() {
      this.editModal = true;
    },

    //分页数据
    changePage(index) {
      this.pageCurrent = index;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //每页显示数据
    changePageSize(size) {
      this.pageSize = size;
      this.getData(this.pageCurrent, this.pageSize);
    },
    requireFormData(data) {
      if (!data.money || data.money <= 0 || data.money > 10000) {
        this.$Message.warning("您输入的金额应在0-10000之间，请重新输入.");
        return false;
      } else if (!data.date || data.date.length !== 10) {
        this.$Message.warning("您未选择日期或格式错误，请重新输入.");
        return false;
      } else if (data.name.length > 20 || !data.name) {
        this.$Message.warning(
          "您输入的商品名称格式错误，字数在1-1000位之间，请重新输入."
        );
        return false;
      } else if (data.mode < 0) {
        this.$Message.warning("您未选择支付方式或格式错误，请选择支付方式.");
        return false;
      } else {
        return true;
      }
    },
    formatDate() {
      let nowDate = new Date();
      let y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = nowDate.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + m + "-" + d;
    },
  },
  created() {
    this.pageSize = this.$store.state.pageSize;
    this.getData(this.page, this.pageSize);
  },
  watch: {
    searchTypeValue(value) {
      this.searchInputType = value == "date" ? "date" : "text";
    },
  },
  mounted() {
    this.addData.date = this.formatDate();
  },
};
</script>
<style>
  .mb10{
    margin-bottom: 10px !important;
  }
</style>